﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace GBits.ContactUtilites
{
    public class DataAccess
    {
        private static DataAccess _dataAccess = null;
        private const string lead = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
        private string header = "<ContactManager program=\"Contact Manager\" version=\"" + Assembly.GetExecutingAssembly().GetName().Version.ToString() + "\">";
        private const string footer = "</ContactManager>";

        public static DataAccess GetData()
        {
            if (_dataAccess == null)
                _dataAccess = new DataAccess();
            return _dataAccess;
        }

        public DataAccess()
        {
            //dataPath = UserOptions.dataDirectory();
        }

        public void SaveContact(MyContact contact, string outName)
        {
            string xml = lead + header + contact.ToXml() + footer;
            string filename = outName;

            XmlDocument outDoc = new XmlDocument();
            
            outDoc.LoadXml(xml);
            XmlNode tempRoot = outDoc.SelectSingleNode("ContactManager");
            if (tempRoot == null) return;

            XmlNode nodeToAdd = outDoc.CreateNode(XmlNodeType.Element, "Item", null);
            foreach (XmlAttribute a in tempRoot.Attributes)
            {
                XmlAttribute newAttr = outDoc.CreateAttribute(a.Name);
                newAttr.Value = a.Value;
                nodeToAdd.Attributes.Append(newAttr);
            }

            nodeToAdd.InnerXml = tempRoot.InnerXml;
            outDoc.Save(filename);
        }

        public void SaveOptions(string optionXML)
        {
            string xml = lead + header + optionXML + footer;
            string filename = Application.StartupPath + @"\Data\UserOptions.opt";

            XmlDocument outDoc = new XmlDocument();

            outDoc.LoadXml(xml);
            XmlNode tempRoot = outDoc.SelectSingleNode("ContactManager");
            if (tempRoot == null) return;

            XmlNode nodeToAdd = outDoc.CreateNode(XmlNodeType.Element, "Item", null);
            foreach (XmlAttribute a in tempRoot.Attributes)
            {
                XmlAttribute newAttr = outDoc.CreateAttribute(a.Name);
                newAttr.Value = a.Value;
                nodeToAdd.Attributes.Append(newAttr);
            }

            nodeToAdd.InnerXml = tempRoot.InnerXml;
            outDoc.Save(filename);
        }

        public string ExportFile(string filename, string contents)
        {
            try
            {
                File.WriteAllText(filename, contents);
            }
            catch
            {
                return "Error writing file, make sure no other application is using the file";
            }
            return "";
        }

        public void GetOptions()
        {
            XmlTextReader reader = new XmlTextReader(Application.StartupPath + @"\Data\UserOptions.opt");
            //string xml = reader.ReadInnerXml();

            while (reader.Read())
            {
                if(reader.NodeType == XmlNodeType.Element && reader.Name == "Option")
                {
                    reader.MoveToFirstAttribute();
                    switch(reader.Value)
                    {
                        case "treeDock":
                            reader.MoveToNextAttribute();
                            if (reader.Value == "Right")
                                UserOptions.treeDock = DockStyle.Right;
                            else UserOptions.treeDock = DockStyle.Left;
                            break;
                        case "helpDock":
                            reader.MoveToNextAttribute();
                            if (reader.Value == "Right")
                                UserOptions.helpDock = DockStyle.Right;
                            else UserOptions.helpDock = DockStyle.Left;
                            break;
                        case "toolbarVisible":
                            reader.MoveToNextAttribute();
                            if (reader.Value == "True")
                                UserOptions.toolbarVisible = true;
                            else UserOptions.toolbarVisible = false;
                            break;
                        case "dataDirectory":
                            reader.MoveToNextAttribute();
                            if(reader.Value == "")
                                UserOptions.dataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                            else UserOptions.dataDirectory = reader.Value;
                            break;
                        case "eventDock":
                            reader.MoveToNextAttribute();
                            if (reader.Value == "Right")
                                UserOptions.eventDock = DockStyle.Right;
                            else UserOptions.eventDock = DockStyle.Left;
                            break;
                        default:
                            break;

                    }

                }
            }
            //Console.WriteLine(xml);
        }

        public MyContact GetContact(string filename)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(filename);
            XmlNode root = doc.SelectSingleNode("ContactManager");
            if (root.Attributes["version"].Value != Assembly.GetExecutingAssembly().GetName().Version.ToString())
            {
                MessageBox.Show("Product Version and file version do not match." + '\n' + "Could result in errors reading the file.", "File Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            string xml = root.InnerXml;
            return new MyContact(xml);
        }

        public DataTable GetSimpleContactList()
        {
            string[] filePaths = Directory.GetFiles(UserOptions.dataDirectory);
            DataTable results = new DataTable();
            results.Columns.Add("id",typeof(string));
            results.Columns.Add("name", typeof(string));

            for (int i = 0; i < filePaths.Length; i++)
            {
                if(filePaths[i].EndsWith("gbc"))
                {
                    results.Rows.Add();
                    //Console.WriteLine(filePaths[i]);
                    XmlDocument TempDoc = new XmlDocument();
                    TempDoc.Load(filePaths[i]);
                    XmlNode root = TempDoc.SelectSingleNode("ContactManager");
                    XmlNode node = root.SelectSingleNode("Contact");
                    //XmlNode node = TempDoc.SelectSingleNode("Contact");
                    results.Rows[results.Rows.Count - 1][0] = node.Attributes["id"].Value;
                    results.Rows[results.Rows.Count - 1][1] = node.Attributes["name"].Value;
                }
            }
            results.DefaultView.Sort = "name ASC";
            return results;
        }

        public DataTable GetTreeContactList()
        {
            string[] filePaths = Directory.GetFiles(UserOptions.dataDirectory);
            DataTable results = new DataTable();
            results.Columns.Add("id", typeof(string));
            results.Columns.Add("name", typeof(string));
            results.Columns.Add("organization", typeof(string));

            for (int i = 0; i < filePaths.Length; i++)
            {
                if (filePaths[i].EndsWith("gbc"))
                {
                    results.Rows.Add();
                    //Console.WriteLine(filePaths[i]);
                    XmlDocument TempDoc = new XmlDocument();
                    TempDoc.Load(filePaths[i]);
                    XmlNode root = TempDoc.SelectSingleNode("ContactManager");
                    XmlNode node = root.SelectSingleNode("Contact");
                    //XmlNode node = TempDoc.SelectSingleNode("Contact");
                    results.Rows[results.Rows.Count - 1][0] = node.Attributes["id"].Value;
                    results.Rows[results.Rows.Count - 1][1] = node.Attributes["name"].Value;
                    results.Rows[results.Rows.Count - 1][2] = node.Attributes["organization"].Value;
                }
            }
            results.DefaultView.Sort = "organization ASC";
            return results;
        }

    }
}
